<template>
	<view>
		<view class="loading-cover" v-show="isLoading"></view>
		<view class="editaddress-container">
			<view class="editaddress-header">
				<!-- #ifdef MP-WEIXIN -->
				<!-- 微信小程序中不显示按钮 -->
				<!-- #endif -->

				<!-- #ifndef MP-WEIXIN -->
				<!-- 非微信小程序平台（包括iOS和Android）显示按钮 -->
				<view class="back-icon">
					<uni-icons type="left" size="25" @click="backAddressList()"></uni-icons>
				</view>
				<!-- #endif -->
				<view class="title">
					{{title}}
				</view>
			</view>
			<view class="editaddress-content">
				<view class="consignee-box">
					<view class="consignee-box-content">
						<view class="consignee-item">
							<view class="consignee-text">
								收货人
							</view>
							<input class="consignee-item-input" placeholder="请输入收货人姓名" type="text"
								v-model="saveAddrData.name" />
						</view>
						<view class="consignee-item">
							<view class="consignee-text">
								手机号码 +86
							</view>
							<input class="consignee-item-input" placeholder="请填写手机号码" type="text"
								v-model="saveAddrData.phone" />
						</view>
						<view class="consignee-item">
							<view class="consignee-text">
								所在地区
							</view>
							<view class="like-input-view">
								<uni-data-picker placeholder="省市区县/乡镇" :localdata="areaList" popup-title="请选择所在地区"
									v-model="selectedArea" @change="getBaseArea"></uni-data-picker>
							</view>
							<view class="right-icon">
								<uni-icons class="arrow-right" color="#999" type="right" size="18"></uni-icons>
							</view>
						</view>
						<view class="consignee-item">
							<view class="consignee-text">
								详细地址
							</view>
							<input class="consignee-item-input" placeholder="街道/楼牌号等" type="text"
								v-model="saveAddrData.address" />
						</view>
					</view>
				</view>
			</view>
		</view>
		<uni-popup ref="messageRef" type="message">
			<uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message>
		</uni-popup>
		<view class="save-btn-box">
			<view class="save-btn" @click="saveAddress()">
				保存
			</view>
		</view>

	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		watch,
		watchEffect,
		onBeforeMount
	} from 'vue';
	import {
		sharedState
	} from '@/common/store.js';
	import {
		areaList
	} from '@/common/area.js';
	import {
		onShow,
		onHide,
		onUnload,
		onLoad
	} from '@dcloudio/uni-app';
	const msgType = ref('success');
	//消息提示窗初始化
	const messageText = ref(null);
	//绑定消息提示窗
	const messageRef = ref(null);
	//标题信息初始化
	let title = ref("新建地址信息");
	//缓存到localStorage的地址数组
	let addressList = ref([]);

	const selectedArea = ref([]); // 新增 selectedArea 用来绑定 uni-data-picker 的值
	let isLoading = ref(false);
	//装填编辑和新增的地址数据的容器
	let saveAddrData = ref({
		userId: "",
		name: "",
		phone: "",
		province: "",
		city: "",
		district: "",
		address: ""
	})
	//消息弹窗触发方法
	const messageToggle = (typeValue) => {
		if (messageRef.value) {
			messageRef.value.open(); // 使用 messageRef 打开提示框
		} else {
			console.warn('messageRef is not yet available'); // 添加日志输出
		}
	};
    
	//获取省市区级联选择器的数据赋值给saveAddrData.baseAddress
	let getBaseArea = (e) => {
		console.log("sdadasdasdasd", e.detail.value);
		// console.log(selectedArea.value);
		saveAddrData.value.province = e.detail.value[0].text;
		saveAddrData.value.city = e.detail.value[1].text;
		saveAddrData.value.district = e.detail.value[2].text;
		let testData = e.detail.value[0].text + e.detail.value[1].text + e.detail.value[2].text;

		console.log(testData);
	}
	//返回观演人列表页面
	let backAddressList = () => {
		uni.navigateBack({
			delta: 1
		})
	}

	const getAddrDataById = () => {
		const addrId = sharedState.value;
		uni.request({
			url: `/st/addrDetail/${addrId}`,
			method: 'GET',
			success: (res) => {
				if (res.data.code == 2000) {
					saveAddrData.value = res.data.data;
					console.log(saveAddrData.value);
					selectedArea.value = [{text:'',value:0},{text:'',value:0},{text:'',value:0}];
			const selectProvince = areaList.find(addr => addr.text ===  res.data.data.province);
			const selectCity =  selectProvince.children.find(addr => addr.text ===  res.data.data.city);
			const selectDistrict =  selectCity.children.find(addr => addr.text ===  res.data.data.district);
					selectedArea.value[0].text = res.data.data.province;
					selectedArea.value[0].value = selectProvince.value;
					selectedArea.value[1].text = res.data.data.city;
					selectedArea.value[1].value = selectCity.value;
					selectedArea.value[2].text = res.data.data.district;
					selectedArea.value[2].value = selectDistrict.value;
				}
			},
			fail: () => {

			},
		})
	}

	//保存地址
	let saveAddress = () => {

		console.log(saveAddrData.value);

		if (
			!saveAddrData.value.userId ||
			!saveAddrData.value.name ||
			!saveAddrData.value.phone ||
			!saveAddrData.value.province ||
			!saveAddrData.value.city ||
			!saveAddrData.value.district ||
			!saveAddrData.value.address
		) {
			console.log("错误")
			msgType.value = 'error';
			messageText.value = '请填写完整的地址';
			messageToggle('error');
		} else {
			if (sharedState.value != null) {
				uni.request({
					url: "/st/addrDetail/update",
					method: "PUT",
					data: saveAddrData.value,
					success: (res) => {
						console.log(res.data);
						uni.redirectTo({
							url:"/pages/address/address"
						})
					},
					fail: () => {
				
					},
				
				})
			} else {
				uni.request({
					url: "/st/addrDetail/addAddr",
					method: "POST",
					data: saveAddrData.value,
					success: (res) => {
						console.log(res.data);
						uni.redirectTo({
							url:"/pages/address/address"
						})
					},
					fail: () => {

					},

				})
			}
		}

	}



	watchEffect(() => {
		console.log(sharedState.value);
		//监控观演人列表传过来的id是否存在判断显示新建还是编辑，删除按钮显隐
		if (sharedState.value == null) {
			title = "新建地址信息";
		} else {
			title = "编辑地址信息";
		}
	});

	onBeforeMount(() => {
		
		if(sharedState.value!=null){
			isLoading.value = true;
			uni.showLoading({
			      title: '加载中'
			    });
		}
	
			
			uni.getStorage({
				key: 'userLogin',
				success: function(res) {
					saveAddrData.value.userId = res.data.id;
				},
				fail: function(err) {
					console.error('获取数据失败', err);
				}
			});
			
			getAddrDataById();
			  setTimeout(() => {
			 
			      uni.hideLoading();
				  isLoading.value = false;
			    }, 200);
		
		console.log(areaList);
	});
</script>

<style lang="scss" scoped>
	.editaddress-container {
		width: 100%;
		min-height: 100vh;
		height: auto;
		display: block;
		background: #f8f8fe;
		color: #333;

		.editaddress-header {
			float: left;
			width: 100%;
			height: 50px;
			top: 0px;
			position: fixed;
			display: flex;
			z-index: 1000;
			background: #fff;
			box-sizing: border-box;
			text-align: center;
			justify-content: center;
			align-items: center;

			.title {
				position: absolute;
				line-height: 50px;
				font-size: 18px;
				z-index: 5;
				height: 50px;
			}

			.back-icon {
				z-index: 10;
				position: absolute;
				left: 10px;
			}

			.delete-btn {
				height: 50px;
				z-index: 10;
				line-height: 50px;
				font-size: 16px;
				position: absolute;
				right: 15px;
			}
		}

		.editaddress-content {
			width: 100%;
			height: auto;
			background: #f8f8fe;
			float: left;
			margin-top: 50px;

			.consignee-box {
				width: 100%;
				height: auto;
				float: left;
				background: #fff;

				.consignee-box-content {
					.consignee-item {
						width: 100%;
						height: 50px;
						line-height: 50px;
						float: left;
						padding: 0px 15px;
						box-sizing: border-box;
						border-top: 1px solid #ddd;

						.consignee-text {
							height: 50px;
							width: 90px;
							line-height: 50px;
							font-size: 14px;
							float: left;
						}

						.consignee-item-input {
							width: calc(100% - 90px);
							height: 50px;
							line-height: 50px;
							float: left;
							border: none;
							box-sizing: border-box;
							padding-left: 10px;
							font-size: 14px;


						}

						.like-input-view {
							width: calc(100% - 120px);
							height: 50px;
							line-height: 50px;
							float: left;
							border: none;
							box-sizing: border-box;
							font-size: 14px;
							color: #333;
						}

						.right-icon {
							width: auto;
							height: 50px;
							float: right;

							.arrow-right {
								line-height: 50px;
							}
						}

						.consignee-item:last-child {
							box-shadow: 0px 0px 4px 0px #ddd;
							background: red;
						}
					}


				}
			}
		}
	}


	.save-btn-box {
		width: 100%;
		height: 80px;
		background: #fff;
		box-sizing: border-box;
		padding: 20px 15px;
		position: fixed;
		bottom: 0px;
		z-index: 50;
		box-shadow: 0px 0px 4px 0px #d3d3d3;

		.save-btn {
			width: 100%;
			height: 40px;
			font-size: 14px;
			background: #ff2d2de2;
			color: #fff;
			border-radius: 4px;
			line-height: 40px;
			text-align: center;
		}
	}


	//刺穿uniapp的css

	:deep {
		.input-value {
			display: block !important;
		}

		.input-value-border {
			border: none;
		}

		.selected-item {
			padding: 0px;
		}

		.item {
			padding: 0px 15px;
		}

		.placeholder {
			font-size: 14px;
		}
	}
	
	.loading-cover {
		width: 100%;
		height: 100vh;
		background: #fff;
		position: fixed;
		top: 0px;
		z-index: 100;
	}
</style>